package com.travel.Controller.User;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.travel.Bean.Ticket;
import com.travel.Bean.Trade;
import com.travel.Bean.Record;
import com.travel.JPA.TicketJPA;
import com.travel.JPA.TradeJPA;
import com.travel.JPA.RecordTypeJPA;
import com.travel.Pojo.TicketAndCultureName;
import com.travel.Service.Impl.AlipayServiceImpl;
import com.travel.Service.Impl.TicketServiceImpl;
import com.travel.Service.Impl.RecordServiceImpl;
import com.travel.util.Alipay;
import com.travel.util.ConsoleOutputControl;
import com.travel.util.R;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("Ticket")
public class UserTicketController {

    @Autowired
    private TicketJPA ticketJPA;
    @Autowired
    private RecordTypeJPA recordTypeJPA;
    @Autowired
    private TicketServiceImpl ticketService;
    @Autowired
    private AlipayServiceImpl alipayService;

    @Autowired
    private RecordServiceImpl recordService;
    @Autowired
    private TradeJPA tradeJPA;

    @Autowired
    private ObjectMapper objectMapper;

    //获取用户id
    public String getUserId() {
        String username;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }


    /**
     * 得到项目
     *
     * @param ticketId 项目id
     * @return {@link R}
     */
    @ApiOperation("获取景区项目信息")
    @ApiImplicitParam(name = "ticketId",value = "项目id")
    @PostMapping("getTicket")
    public R getTicket(Integer ticketId) {
        Ticket ticket = ticketService.getTicketById(ticketId);
        return R.ok(0,ticket);
    }

    /**
     * 得到项目列表
     *
     * @param ticketName 项目名字
     * @param cultureId  景区id
     * @param page       页面
     * @param limit      记录条数
     * @return {@link R}
     */
    @ApiOperation("获取项目列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ticketName",value = "项目名称，用于模糊搜索"),
            @ApiImplicitParam(name = "cultureId",value = "必选参数，用于查看cultureId景区下的项目")
    })
    @PostMapping("getTicketList")
    public R getTicketList(String ticketName,Integer cultureId,@RequestParam(defaultValue = "1")Integer page,
                           @RequestParam(defaultValue = "15")Integer limit){
        PageInfo<TicketAndCultureName> pageInfo;
        try{
            pageInfo = ticketService.selTicketList(ticketName,cultureId,page,limit,false);
        }catch (Exception e){
            e.printStackTrace();
            ConsoleOutputControl.getOutputString_33("获取项目列表,getTicketList,获取项目列表出错\n" +
                    "ticketName："+ticketName+"___cultureId:"+ cultureId);
            return R.no(1,"获取项目列表失败");
        }
        return R.ok("0",pageInfo.getList(),pageInfo.getTotal());

    }


    /**
     * 购买门票
     *
     * @param record  景区信息
     * @param response 响应
     * @throws IOException ioexception
     */
    @ApiOperation("购买门票")
    @ApiResponses({
            @ApiResponse(code = 4003, message = "订单发起失败")
    })
    @RequestMapping("/purchaseTickets")
    public void purchaseTickets(@RequestBody List<Record> record, HttpServletResponse response) throws IOException {
         int recordId = 101;
        Trade trade = new Trade();

        DateTimeFormatter Formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        DateTimeFormatter TimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime today = LocalDateTime.now();
        //z转换sqlDate
        Date sqlDate =  Date.valueOf(today.format(Formatter));
        //同时购买多张票，使用同一订单号
        String OrderID = today.format(Formatter) + record.get(0).getTicket_id() + recordId ;
        //记录订单号和订单发起时间
        trade.setOrder_id(OrderID);
        trade.setAtom_time(sqlDate);

        String recordID =  today.format(Formatter) + record.get(0).getTicket_id();
        float price = 0.0F;
        for (Record value : record) {
            float p;
            value.setRecord_userid(getUserId());
            //设置统一订单号
            value.setOrder_id(OrderID);
            //设置不同的门票id
            value.setRecord_id(recordID + (++recordId));
            //设置为待支付状态
            value.setRecord_state("6");
            value.setRecord_time(today.format(TimeFormatter));
            p = (recordTypeJPA.findByRecord_type(Integer.parseInt(value.getRecord_type()))*0.01F)*ticketService.getTicketPrice(value.getTicket_id());
            value.setRecord_amount(p);
            //计算订单的总金额
            price+= p;
        }
        //保存订单总金额
        trade.setTotal_amount(price);
        //记录交易中间方
        trade.setTrade("ZFB");
        //保存已有的订单信息
        tradeJPA.save(trade);
        //获取项目名称设置订单名陈
        String ticketName = ticketService.getTicketName(record.get(0).getTicket_id());
        //保存购票记录，订单信息
        //如果订单记录保存失败，则打印失败信息，并返回订单发起失败
        if (recordService.saveRecord_6(record)>0){

            ConsoleOutputControl.getOutputString_33("订单服务发起失败——recordService");

            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            PrintWriter out = response.getWriter();
            Map<String,Object> map = new HashMap<>();
            map.put("code",4003);
            map.put("msg","订单发起失败");
            out.write(objectMapper.writeValueAsString(map));
            out.flush();
            out.close();
        }
        //发起支付，调用支付宝的支付接口
        alipayService.payController(response, Alipay.pay_3(OrderID, Float.toString(price),ticketName));
    }


    /**
     * 阿里支付通知
     *
     * @param request  请求
     * @param response 响应
     */
    @ApiOperation("支付宝支付，异步回调接口")
    @RequestMapping("/AliPayNotify")
    public void AliPayNotify(HttpServletRequest request,HttpServletResponse response){

        alipayService.AliPayNotify(request,response);

    }


    @ApiOperation("/支付测试接口")
    @RequestMapping("/AliPayTest")
    public void AliPayTest(HttpServletResponse response, String orderNumber) throws IOException {
        alipayService.payController(response, Alipay.pay_3(orderNumber,"1.11","towelTest"));
    }


}
